package com.system.boss.openssl.service;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;

import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.system.boss.openssl.mapper.SysOpensslMapper;
import com.system.boss.openssl.model.SysOpenssl;

import lombok.extern.slf4j.Slf4j;

@Service
@Slf4j
public class OpenSSLBackupService {

	@Autowired
	private SysOpensslMapper sysOpensslMapper;

	@Autowired
	private OpenSSLGenTool openSSLGenTool;

	public void opensslBackup(OutputStream outstream) throws Exception {

		List<SysOpenssl> list = sysOpensslMapper.selectByExample(null);

		String jsonstring = JSONArray.toJSONString(list);

		File homedir = new File(openSSLGenTool.getHomedir());
		ZipOutputStream zipos = new ZipOutputStream(outstream);

		for (File tmp : homedir.listFiles()) {
			if (tmp.isFile()) {
				zipos.putNextEntry(new ZipEntry(tmp.getName()));
				FileInputStream fis = new FileInputStream(tmp);
				IOUtils.copy(fis, zipos);
				fis.close();
			} else {
				zipos.putNextEntry(new ZipEntry(tmp.getName() + "/"));
			}
		}

		zipos.putNextEntry(new ZipEntry("data.json"));
		zipos.write(jsonstring.getBytes());

		zipos.flush();
		zipos.close();

		outstream.flush();
		outstream.close();
	}

	public void opensslRestoreBackup(InputStream is) throws Exception {
		
		sysOpensslMapper.deleteByExample(null);
		
		SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
		File workspace = new File(openSSLGenTool.getHomedir());
		File backup = new File(workspace.getParentFile().getAbsolutePath(),
				"cer_backup" + format.format(Calendar.getInstance().getTime()));
		File srouce = new File(openSSLGenTool.getHomedir());
		log.debug("从{}备份文件到：{}", srouce.getAbsolutePath(), backup.getAbsolutePath());
		if (workspace.exists()) {
			Files.move(Paths.get(srouce.toURI()), Paths.get(backup.toURI()), StandardCopyOption.REPLACE_EXISTING);
		}

		workspace.mkdirs();

		ZipInputStream zis = new ZipInputStream(is);

		ZipEntry zipEntry = null;

		while ((zipEntry = zis.getNextEntry()) != null) {
			if (!zipEntry.isDirectory()) {
				File unzipedFile = new File(openSSLGenTool.getHomedir(), zipEntry.getName());
				FileOutputStream fos = new FileOutputStream(unzipedFile);
				IOUtils.copy(zis, fos);
				fos.flush();
				fos.close();
			} else {
				File unzipedFolder = new File(openSSLGenTool.getHomedir(), zipEntry.getName());
				if (!unzipedFolder.exists()) {
					unzipedFolder.mkdirs();
				}
			}
		}
		zis.close();

		File datajson = new File(workspace, "data.json");
		if (datajson.exists()) {
			FileInputStream fis = new FileInputStream(datajson);
			List<SysOpenssl> list = JSONArray.parseArray(IOUtils.toString(fis,"utf-8"), SysOpenssl.class);
			fis.close();
			for(SysOpenssl sysOpenssl:list) {
				sysOpensslMapper.insert(sysOpenssl);
			}
			datajson.delete();
		}
	}
}
